package com.app.island.cash.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.app.island.cash.R
import com.app.island.cash.adapter.CodeAdapter.ContactHolder
import com.app.island.cash.databinding.AdapterIfscLayoutBinding
import com.app.island.cash.data.sigle.CodeListBack
import java.util.*

class CodeAdapter(private val mContext: Context) : RecyclerView.Adapter<ContactHolder>() {
    private val beanList: MutableList<CodeListBack.Bean>
    private var onItemClickListener: OnItemClickListener? = null
    private var selected = 0

    inner class ContactHolder(val binding: AdapterIfscLayoutBinding) : RecyclerView.ViewHolder(
        binding.root
    )

    fun setSelected(selected: Int) {
        this.selected = selected
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        this.onItemClickListener = onItemClickListener
    }

    fun setList(data: List<CodeListBack.Bean>?) {
        beanList.clear()
        beanList.addAll(data!!)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return beanList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactHolder {
        return ContactHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.adapter_ifsc_layout,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ContactHolder, position: Int) {
        val contact = beanList[position]
        holder.binding.ivTitle.text = contact.name
        holder.binding.tvDesc.text = if (contact.grade == 4) contact.address else ""
        holder.binding.tvDesc.visibility = if (contact.grade == 4) View.VISIBLE else View.GONE
        holder.binding.root.setOnClickListener { v ->
            if (onItemClickListener != null) onItemClickListener!!.OnItemClick(
                v,
                contact,
                position
            )
        }
        if (contact.grade == 1 || contact.grade == 2 || contact.grade == 3) {
            selected = -1
        }
        if (selected == position) {
            holder.binding.ivTitle.setTextColor(mContext.resources.getColor(R.color.color_4071ff))
            holder.binding.tvDesc.setTextColor(mContext.resources.getColor(R.color.color_4071ff))
        } else {
            holder.binding.ivTitle.setTextColor(mContext.resources.getColor(R.color.color_333))
            holder.binding.tvDesc.setTextColor(mContext.resources.getColor(R.color.color_333))
        }
    }

    interface OnItemClickListener {
        fun OnItemClick(view: View?, item: CodeListBack.Bean, position: Int)
    }

    init {
        beanList = ArrayList()
    }
}